//
//  SinaStatusListViewModel.swift
//  WeiBo
//
//  Created by Apple on 16/1/4.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

class SinaStatusListViewModel: NSObject {

    lazy var list: [SinaStatusViewModel] = [SinaStatusViewModel]()
    
    func getData(since_id: Int, success:(count: Int) -> (),failure:() -> ()){
        
        // 1 创建一个 afn实例
        let afn = AFHTTPSessionManager()
        
        // 2 拼接参数
        //access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得
        let params = ["access_token":SinaAccountViewModel.shareInstance.access_token,"since_id":since_id]
        
        // 3 发送一个 get 请求
        afn.GET("https://api.weibo.com/2/statuses/home_timeline.json", parameters: params, success: { (_, JSON) -> Void in
            //            printLog(JSON)
            
            if let dic = JSON as? [String: AnyObject]{
                
                // 一定要确保有数据,再强制解包
                let statues = dic["statuses"] as! [[String: AnyObject]]
                
                var temp: [SinaStatusViewModel] = [SinaStatusViewModel]()
                
                // 便利
                for status in statues {
                    
                    let statusModel = SinaStatusModel(dic: status)
                    
                    
                    // 添加到数组里
                    temp.append(SinaStatusViewModel(statusModel: statusModel))
                }
                
                if since_id > 0 {
                    //数据拼接
                    self.list = temp + self.list
                }else{
                    self.list = temp
                }
                
                // 拼接数据完成之后,回调
                    success(count: temp.count)
                
            }
            
            }) { (_ , error) -> Void in
                printLog(error)
                
        }
        
        
    }
    
}
